/**
 * @file test_connection_diagnosis.cpp
 * @brief 连接诊断测试程序
 * 
 * 用于测试和验证游戏状态消息处理链路的完整性
 */

#include <QCoreApplication>
#include <QJsonObject>
#include <QJsonDocument>
#include <QDebug>
#include <QTimer>
#include <QThread>

// 模拟服务器发送的消息
const QString TEST_MESSAGE = R"({
    "data": {
        "foods": [
            {
                "age_ms": 815,
                "expired": false,
                "lifetime_ms": 30000,
                "object_type": "food",
                "position": {
                    "type": "position",
                    "x": 23,
                    "y": 7
                },
                "render_info": {
                    "alpha": 1.0,
                    "rotation": 0.0,
                    "scale": 1.0
                },
                "spawn_time": 1755094287101,
                "sprite_name": "apple",
                "type": 0,
                "value": 1
            }
        ],
        "game_info": {
            "alive_players": 1,
            "current_food_count": 6,
            "duration_seconds": 68,
            "food_spawn_rate": 5,
            "max_food_count": 10,
            "speed_ms": 100,
            "total_players": 1
        },
        "snakes": [
            {
                "alive": true,
                "body": [
                    {
                        "type": "position",
                        "x": 13,
                        "y": 5
                    },
                    {
                        "type": "position",
                        "x": 12,
                        "y": 5
                    },
                    {
                        "type": "position",
                        "x": 11,
                        "y": 5
                    }
                ],
                "color": "#00FF00",
                "direction": 3,
                "head": {
                    "type": "position",
                    "x": 13,
                    "y": 5
                },
                "last_move": 1755094287915,
                "length": 3,
                "player_id": "temp_9882115941467850485_40_1755094168120",
                "player_name": "temp_9882115941467850485_40_1755094168120",
                "score": 0,
                "speed": 100,
                "tail": {
                    "type": "position",
                    "x": 11,
                    "y": 5
                },
                "type": "snake"
            }
        ],
        "status": 0,
        "tick_count": 8,
        "timestamp": 1755094287915
    },
    "qt6_optimized": true,
    "timestamp": 1755094287917,
    "type": "game_state_update"
})";

class ConnectionDiagnosisTest : public QObject
{
    Q_OBJECT

public:
    ConnectionDiagnosisTest(QObject *parent = nullptr) : QObject(parent) {}

    void runTests()
    {
        qDebug() << "=== 连接诊断测试开始 ===";
        
        // 测试1：消息解析
        testMessageParsing();
        
        // 测试2：数据字段访问
        testDataFieldAccess();
        
        // 测试3：游戏数据提取
        testGameDataExtraction();
        
        qDebug() << "=== 连接诊断测试完成 ===";
        
        // 延迟退出
        QTimer::singleShot(1000, qApp, &QCoreApplication::quit);
    }

private:
    void testMessageParsing()
    {
        qDebug() << "\n--- 测试1：消息解析 ---";
        
        QJsonParseError error;
        QJsonDocument doc = QJsonDocument::fromJson(TEST_MESSAGE.toUtf8(), &error);
        
        if (error.error != QJsonParseError::NoError) {
            qCritical() << "❌ JSON解析失败:" << error.errorString();
            return;
        }
        
        QJsonObject message = doc.object();
        QString messageType = message["type"].toString();
        
        qDebug() << "✅ JSON解析成功";
        qDebug() << "   消息类型:" << messageType;
        qDebug() << "   qt6_optimized:" << message["qt6_optimized"].toBool();
        qDebug() << "   timestamp:" << message["timestamp"].toVariant().toLongLong();
        qDebug() << "   包含data字段:" << message.contains("data");
    }
    
    void testDataFieldAccess()
    {
        qDebug() << "\n--- 测试2：数据字段访问 ---";
        
        QJsonDocument doc = QJsonDocument::fromJson(TEST_MESSAGE.toUtf8());
        QJsonObject message = doc.object();
        QJsonObject data = message["data"].toObject();
        
        if (data.isEmpty()) {
            qCritical() << "❌ data字段为空或不存在";
            return;
        }
        
        qDebug() << "✅ data字段访问成功";
        qDebug() << "   包含snakes:" << data.contains("snakes");
        qDebug() << "   包含foods:" << data.contains("foods");
        qDebug() << "   包含game_info:" << data.contains("game_info");
        
        // 检查数组大小
        QJsonArray snakes = data["snakes"].toArray();
        QJsonArray foods = data["foods"].toArray();
        
        qDebug() << "   蛇数量:" << snakes.size();
        qDebug() << "   食物数量:" << foods.size();
    }
    
    void testGameDataExtraction()
    {
        qDebug() << "\n--- 测试3：游戏数据提取 ---";
        
        QJsonDocument doc = QJsonDocument::fromJson(TEST_MESSAGE.toUtf8());
        QJsonObject message = doc.object();
        QJsonObject data = message["data"].toObject();
        
        // 提取蛇数据
        QJsonArray snakes = data["snakes"].toArray();
        if (!snakes.isEmpty()) {
            QJsonObject snake = snakes[0].toObject();
            qDebug() << "✅ 蛇数据提取成功";
            qDebug() << "   玩家ID:" << snake["player_id"].toString();
            qDebug() << "   分数:" << snake["score"].toInt();
            qDebug() << "   方向:" << snake["direction"].toInt();
            qDebug() << "   存活:" << snake["alive"].toBool();
            qDebug() << "   身体长度:" << snake["body"].toArray().size();
        }
        
        // 提取游戏信息
        QJsonObject gameInfo = data["game_info"].toObject();
        if (!gameInfo.isEmpty()) {
            qDebug() << "✅ 游戏信息提取成功";
            qDebug() << "   存活玩家:" << gameInfo["alive_players"].toInt();
            qDebug() << "   总玩家:" << gameInfo["total_players"].toInt();
            qDebug() << "   游戏速度:" << gameInfo["speed_ms"].toInt();
            qDebug() << "   当前食物数:" << gameInfo["current_food_count"].toInt();
        }
        
        // 提取食物数据
        QJsonArray foods = data["foods"].toArray();
        if (!foods.isEmpty()) {
            QJsonObject food = foods[0].toObject();
            QJsonObject position = food["position"].toObject();
            qDebug() << "✅ 食物数据提取成功";
            qDebug() << "   第一个食物位置: (" << position["x"].toInt() 
                     << "," << position["y"].toInt() << ")";
            qDebug() << "   精灵名称:" << food["sprite_name"].toString();
            qDebug() << "   价值:" << food["value"].toInt();
        }
    }
};

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    
    ConnectionDiagnosisTest test;
    
    // 立即开始测试
    QTimer::singleShot(0, &test, &ConnectionDiagnosisTest::runTests);
    
    return app.exec();
}

#include "test_connection_diagnosis.moc"
